﻿using UnityEngine;
using UnityEditor;
using System.Threading;
using System.IO;
public class RefrenceMapBuildWindow : EditorWindow
{
    public RefrenceMapBuilder builder;
    public JobExcuteProgress jobExcuteProgress;
    private RefrenceMap _Map;

    private float mbThreshold = 10;
    [MenuItem("引用查找工具/创建引用查找表")]
    public static void OpenBuildWindow()
    {
        var win = EditorWindow.GetWindow<RefrenceMapBuildWindow>();
        win.maxSize = new Vector2(500, 300);
        win.minSize = new Vector2(500, 300);
    }
    [MenuItem("引用查找工具/输出选择物体的引用关系")]
    [MenuItem("Assets/输出选择物体的引用关系")]
    public static void FindRefrence()
    {
        var obj = Selection.activeObject;
        if (obj != null)
        {
            RefrenceMap map = RefrenceMap.ReadFromProjectPathOrCache();
            if (map == null)
            {
                Debug.LogError("必须先构建资源查找表");
                return;
            }

            string path = AssetDatabase.GetAssetPath(Selection.activeObject);
            if (!string.IsNullOrEmpty(path))
            {
                var finded = map.QueryRefrence(path);
                if (finded != null)
                {
                    finded.DebugSelf();
                }
                else
                {
                    Debug.LogError("不在资源引用表中 :" + path);
                }
            }
            else
            {
                Debug.LogError("无法查找到资源存放的路径");
            }
        }
        else
        {
            Debug.LogError("未选择任何物体");
        }
    }

    private void OnEnable()
    {
        _Map = null;
        this.titleContent = new GUIContent("创建引用查找表");
    }
    private void OnGUI()
    {
        GUILayout.Box("引用查找表路径: " + Application.dataPath + "/" + RefrenceMap.MapDataName);
        GUILayout.Box("当前状态: " + GetRefrenceMapStatusText());
        GUILayout.BeginHorizontal();
        GUILayout.Space(10);
        mbThreshold = GUILayout.HorizontalSlider(mbThreshold, 1, 100);
        GUILayout.Label(string.Format("大小阈值 {0}(MB)", mbThreshold));
        GUILayout.EndHorizontal();
        if (GUILayout.Button("创建引用查找表"))
        {
            if (EditorUtility.DisplayDialog("注意", "本地电脑生成至少需要10分钟以上时间,建议使用Jenkins构建", "开始生成", "取消"))
            {
                Build();
            }

        }
    }
    private string GetRefrenceMapStatusText()
    {
        if (!File.Exists(RefrenceMap.MapDataName))
        {
            return "未生成";
        }
        else
        {
            var fileInfo = new FileInfo(RefrenceMap.MapDataName);

            return "已生成 : " + fileInfo.Length / (float)1024 + " (KB)";
        }
    }
    private void Build()
    {
        builder = new RefrenceMapBuilder();
        builder.MainThreadClenaUp();

        var t = new Thread(BuildThread);
        t.Start(Application.dataPath);
        while (true)
        {
            string title = "正在创建资源引用查找表.....";

            if (jobExcuteProgress.totalCount == 0)
            {
                EditorUtility.DisplayProgressBar(title, "任务创建中...", 0);
                continue;
            }
            string workerInfo = string.Empty;
            if (jobExcuteProgress.workerJobList.Length != 0)
            {
                workerInfo += "总工作线程数量: " + jobExcuteProgress.workerJobList.Length;
                for (int i = 0; i < jobExcuteProgress.workerJobList.Length; i++)
                {
                    workerInfo += "[工作线程: " + i + "] 执行任务数量 :" + jobExcuteProgress.workerJobList[i];
                }

            }

            string info = string.Format("总任务进度: {0} / {1} ", jobExcuteProgress.finishCount, jobExcuteProgress.totalCount);
            info += workerInfo;
            float percent = jobExcuteProgress.perCent;
            EditorUtility.DisplayProgressBar(title, info, percent);
            if (percent > 0.99f)
                break;
        }
        t.Join();
        _Map.SaveProjectRefrenceMap();
        _Map = null;
        EditorUtility.ClearProgressBar();
        EditorUtility.DisplayDialog("执行结束", "资源引用查找表构建结束！", "确定");

        ThreadPool.QueueUserWorkItem((i) =>
        {
            RefrenceMap.CleanCache();
            RefrenceMap.ReadFromProjectPathOrCache();
            Debug.Log("FindRefrenceCacheBuild Finish");
        });
    }
    public void BuildThread(object o)
    {
        string path = (string)o;
        _Map = new RefrenceMap();
        builder.checkMBThreshold = mbThreshold;
        builder.BuildRefrenceMap(_Map, UpdateProgress);


    }
    public void UpdateProgress(JobExcuteProgress p)
    {
        jobExcuteProgress = p;
    }

}